import { FactionService } from "../services/faction.service";
import { SystemMessageService } from "../services/system-message.service";

export interface FactionWsHandler {
  selectedCharacterId?: number;
  factionService: FactionService;
  systemMessageService: SystemMessageService;
  pushMessage: (message: any) => Promise<void>;
}

export const factionWsHandlers: Record<
  number,
  (payload: any, helpers: FactionWsHandler) => Promise<any>
> = {
  // 1236：创建帮派
  1236: async (payload, helpers) => {
    try {
      const { type, name, desc } = payload;

      // 验证参数
      if (!type || !name || !desc) {
        return {
          act_id: 1236,
          code: -1,
          msg: "参数不完整",
        };
      }

      if (typeof type !== "number" || type < 1 || type > 10) {
        return {
          act_id: 1236,
          code: -1,
          msg: "帮派类型无效",
        };
      }

      if (typeof name !== "string" || name.length < 1 || name.length > 20) {
        return {
          act_id: 1236,
          code: -1,
          msg: "帮派名称长度必须在1-20个字符之间",
        };
      }

      // 从helpers获取当前选中的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1236,
          code: -1,
          msg: "请先选择角色",
        };
      }

      // 创建帮派
      const faction = await helpers.factionService.createFaction(
        characterId,
        type,
        name,
        desc
      );

      // 发送系统消息通知
      const factionTypeName = helpers.factionService.getFactionTypeName(type);
      const messageContent = `${factionTypeName}${name}正在成立中,大家可以申请加入了`;

      // 先返回1236成功响应
      const successResponse = {
        act_id: 1236,
        code: 0,
      };

      // 然后发送系统广播260消息
      const systemMessage = {
        act_id: 260,
        code: 0,
        data: {
          c: messageContent,
          h: new Date().toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
          }),
          id: Date.now(),
          n: "系统",
          rid: 1000,
          t: 6,
        },
      };

      // 发送系统广播消息
      await helpers.pushMessage(systemMessage);

      return successResponse;
    } catch (error: any) {
      console.error("创建帮派失败:", error);
      return {
        act_id: 1236,
        code: -1,
        msg: error.message || "创建帮派失败",
      };
    }
  },

  // 1126：帮派信息查询
  1126: async (payload, helpers) => {
    try {
      // 从helpers获取当前选中的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1126,
          code: -1,
          msg: "请先选择角色",
          data: null,
        };
      }

      const factionInfo = await helpers.factionService.getFactionInfo(
        characterId
      );

      if (!factionInfo) {
        return {
          act_id: 1126,
          code: -1,
          msg: "您还没有加入任何帮派",
          data: null,
        };
      }

      return {
        act_id: 1126,
        code: 0,
        data: factionInfo,
      };
    } catch (error: any) {
      console.error("查询帮派信息失败:", error);
      return {
        act_id: 1126,
        code: -1,
        msg: error.message || "查询帮派信息失败",
        data: null,
      };
    }
  },

  // 1218：查询帮派成员
  1218: async (payload, helpers) => {
    try {
      const { id, pageNum = 0 } = payload;

      // 验证参数
      if (!id || typeof id !== "number") {
        return {
          act_id: 1218,
          code: -1,
          msg: "帮派ID不能为空且必须为数字",
          list: [],
        };
      }

      const result = await helpers.factionService.getFactionMembers(
        id,
        pageNum
      );

      return {
        act_id: 1218,
        code: 0,
        list: result.list,
        more: result.more,
      };
    } catch (error: any) {
      console.error("查询帮派成员失败:", error);
      return {
        act_id: 1218,
        code: -1,
        msg: error.message || "查询帮派成员失败",
        list: [],
      };
    }
  },

  // 1226：解散帮派
  1226: async (payload, helpers) => {
    try {
      // 从helpers获取当前选中的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1226,
          code: -1,
          msg: "请先选择角色",
        };
      }

      await helpers.factionService.disbandFaction(characterId);

      return {
        act_id: 1226,
        code: 0,
        msg: "您已成功解散教派",
      };
    } catch (error: any) {
      console.error("解散帮派失败:", error);
      return {
        act_id: 1226,
        code: -1,
        msg: error.message || "解散帮派失败",
      };
    }
  },

  // 1197：申请加入帮派
  1197: async (payload, helpers) => {
    try {
      const { id, type } = payload;

      // 验证参数
      if (!id || typeof id !== "number") {
        return {
          act_id: 1197,
          code: -1,
          msg: "帮派ID不能为空且必须为数字",
        };
      }

      // 从helpers获取当前选中的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1197,
          code: -1,
          msg: "请先选择角色",
        };
      }

      await helpers.factionService.applyToJoinFaction(
        characterId,
        id,
        type || 1
      );

      // 获取帮派名称用于消息
      const factionInfo = await helpers.factionService.getFactionInfo(
        characterId
      );
      const factionName = factionInfo?.name || "未知帮派";

      return {
        act_id: 1197,
        code: 0,
        msg: `您已经成功申请加入${factionName},需要等管理员批准,请耐心等候!`,
      };
    } catch (error: any) {
      console.error("申请加入帮派失败:", error);
      return {
        act_id: 1197,
        code: -1,
        msg: error.message || "申请加入帮派失败",
      };
    }
  },

  // 1193：获取帮派列表
  1193: async (payload, helpers) => {
    try {
      const { type = 3, pageNum = 0 } = payload;

      // 验证参数
      if (typeof type !== "number" || type < 0) {
        return {
          act_id: 1193,
          code: -1,
          msg: "帮派类型参数无效",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      if (typeof pageNum !== "number" || pageNum < 0) {
        return {
          act_id: 1193,
          code: -1,
          msg: "页码参数无效",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      // 获取帮派列表
      const result = await helpers.factionService.getFactionList(
        type,
        pageNum,
        20 // 每页20条
      );

      return {
        act_id: 1193,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.sum,
      };
    } catch (error: any) {
      console.error("获取帮派列表失败:", error);
      return {
        act_id: 1193,
        code: -1,
        msg: error.message || "获取帮派列表失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },
};
